package site.zhanjingbo.shop.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import site.zhanjingbo.shop.meta.Product;
import site.zhanjingbo.shop.meta.User;
import site.zhanjingbo.shop.service.ProductService;
import site.zhanjingbo.shop.service.UserService;
import site.zhanjingbo.shop.utils.Permission;
import site.zhanjingbo.shop.utils.PermissionType;

@Controller
public class UserController {

	@Resource
	private UserService userService;

	@Resource
	private ProductService productService;

	@RequestMapping("/login")
	public String loginPage() {
		return "login";
	}

	@RequestMapping("/api/login")
	public Map<String, Object> login(String username, String password, HttpSession session) {
		Map<String, Object> result = new HashMap<>();
		User user = userService.login(username, password);
		if (user != null) {
			result.put("code", 200);
			result.put("message", "登录成功");
			result.put("result", true);
			session.setAttribute("user", user);
		} else {
			result.put("code", 300);
			result.put("message", "登录失败，检查用户名或密码");
			result.put("result", false);
		}

		return result;
	}

	@Permission(permission = { PermissionType.SELLER, PermissionType.BUYER })
	@RequestMapping("/logout")
	public String loginOut(HttpSession session) {
		session.invalidate();
		return "login";
	}

	@Permission(permission = PermissionType.BUYER)
	@RequestMapping("/account")
	public ModelAndView account(HttpSession session) {
		ModelAndView mav = new ModelAndView();
		User user = (User) session.getAttribute("user");
		List<Product> buyList = productService.getProductsByUser(user);
		mav.addObject("buyList", buyList);
		mav.setViewName("account");
		return mav;
	}
}
